package com.shanghaionstar.user.presenter;

import com.onstar.cn.auth.AuthPinTokenEntity;
import com.onstar.cn.auth.AuthTokenRequestEntity;
import com.onstar.cn.auth.userProfile.ServiceEntitlement;
import com.onstar.cn.auth.userProfile.Subscriber;
import com.onstar.cn.auth.userProfile.Vehicle;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.vehicle.response.features.ServiceFeatureCommandEntity;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.login.service.AuthorService;
import com.shanghaionstar.login.service.LoginSerice;
import com.shanghaionstar.user.iview.IChangeVehicleView;
import com.shanghaionstar.user.service.ChangeVehicleService;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;

import java.util.List;
import java.util.Locale;

import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;

/**
 * Created by 7828wc on 16/8/30.
 */
public class ChangeVehiclePresenter extends BasePresenter<List<Vehicle>> {
    private ChangeVehicleService service;
    private IChangeVehicleView iChangeVehicleView;

    public ChangeVehiclePresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
    }

    @Override
    public void setView(IMVPView<List<Vehicle>> view) {
        super.setView(view);
        this.iChangeVehicleView = (IChangeVehicleView) view;
        service = new ChangeVehicleService(view.onActivity());
        setServiceProvider(service);
    }

    public void switchVehicle(final String selectAccount, final Vehicle selectVehicle,String body) {
        iChangeVehicleView.setLoading(true);
        subscription = service.changeAccount(selectAccount,selectVehicle.getVin(),body)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<Vehicle>() {
                    @Override
                    public void call(Vehicle result) {
                        if (selectAccount.equalsIgnoreCase(ApplicationUtil.getInstance().getAccountId())) {
                            //同一个Account切换账号
                            try {
                                OnstarApplication application = (OnstarApplication) iChangeVehicleView.onActivity().getApplicationContext();
                                ApplicationUtil.getInstance().setCurrentVehicle(selectVehicle);
                                changeSameAccount(selectAccount, selectVehicle,result);
                            } catch (Exception e) {
                                Observable.error(e);
                            }
                        } else {
                            changeOtherAccount();
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        iChangeVehicleView.onResponseError((OnStarException) throwable);
                        iChangeVehicleView.setLoading(false);
                    }
                });
    }

    private Subscriber getSubscriber(String selectAccountID, Vehicle selectVehicle) {
        if (!CommonUtil.isNull(selectVehicle) && !CommonUtil.isNull(selectAccountID) && selectAccountID.equalsIgnoreCase(ApplicationUtil.getInstance().getAccountId())) {
            Subscriber subscriber = new Subscriber();
            subscriber.setApp(null);
            subscriber.setVin(selectVehicle.getVin());
            return subscriber;
        }
        return null;
    }

    private void changeSameAccount(final String selectAccountID, final Vehicle selectVehicle,final Vehicle vehicleEntity) throws OnStarException {
        Observable.defer(new Func0<Observable<ServiceFeatureCommandEntity>>() {
            @Override
            public Observable<ServiceFeatureCommandEntity> call() {
                try {
                    return Observable.just(new LoginSerice(iChangeVehicleView.onActivity()).getVehicleFeatures(getSubscriber(selectAccountID, selectVehicle)));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        }).subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<ServiceFeatureCommandEntity>() {
                    @Override
                    public void call(ServiceFeatureCommandEntity result) {
                        OnstarApplication application = (OnstarApplication) iChangeVehicleView.onActivity().getApplicationContext();
                        // 同一个Account切换车辆需重新更新ServiceEntitlement
                        if (vehicleEntity != null) {
                            List<ServiceEntitlement> serviceEntitlement = vehicleEntity
                                    .getServiceEntitlement();
                            if (serviceEntitlement != null && serviceEntitlement.size() > 0) {
                                ApplicationUtil.getInstance().updateServiceEntitlement(
                                        serviceEntitlement);
                            }
                            // 判断是否为电动车
//                            if (vehicleEntity.getModelDesc().toLowerCase(Locale.CHINA).contains("Volt")
//                                    || vehicleEntity.getModelDesc().toLowerCase(Locale.CHINA)
//                                    .contains("沃蓝达")) {
//                                ApplicationUtil.getInstance().setVolt(true);
//                            } else {
//                                ApplicationUtil.getInstance().setVolt(false);
//                            }
//
//                            // 是否为别克车
//                            if (vehicleEntity.getModelDesc().toLowerCase(Locale.CHINA).contains("buick")
//                                    || vehicleEntity.getModelDesc().indexOf(
//                                    iChangeVehicleView.onActivity().getString(R.string.assistant_buick)) > -1) {
//                                ApplicationUtil.getInstance().setBuick(true);
//                            } else {
//                                ApplicationUtil.getInstance().setBuick(false);
//                            }
                        }
                        iChangeVehicleView.setLoading(false);
                        iChangeVehicleView.switchVehicleSuccess();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        iChangeVehicleView.setLoading(false);
                        iChangeVehicleView.onResponseError((OnStarException) throwable);
                    }
                });
//        subscription = Observable.just(loginService.getVehicleFeatures(getSubscriber(selectAccountID, selectVehicle)))
//                .subscribeOn(mvpScheduler.backgroundThread())
//                .observeOn(mvpScheduler.mainThread())
//                .subscribe(new Action1<ServiceFeatureCommandEntity>() {
//                    @Override
//                    public void call(ServiceFeatureCommandEntity result) {
//                        OnstarApplication application = (OnstarApplication) iChangeVehicleView.onActivity().getApplicationContext();
//                        // 同一个Account切换车辆需重新更新ServiceEntitlement
//                        if(iChangeVehicleView!=null) {
//                            iChangeVehicleView.setLoading(false);
//                        }
//                        if (vehicleEntity != null) {
//                            List<ServiceEntitlement> serviceEntitlement = vehicleEntity
//                                    .getServiceEntitlement();
//                            if (serviceEntitlement != null && serviceEntitlement.size() > 0) {
//                                ApplicationUtil.updateServiceEntitlement(iChangeVehicleView.onActivity(),
//                                        serviceEntitlement);
//                            }
//                            // 判断是否为电动车
//                            if (vehicleEntity.getModel().toLowerCase(Locale.CHINA).contains("Volt")
//                                    || vehicleEntity.getModel().toLowerCase(Locale.CHINA)
//                                    .contains("沃蓝达")) {
//                                application.setVolt(true);
//                            } else {
//                                application.setVolt(false);
//                            }
//
//                            // 是否为别克车
//                            if (vehicleEntity.getModel().toLowerCase(Locale.CHINA).contains("buick")
//                                    || vehicleEntity.getModel().indexOf(
//                                    iChangeVehicleView.onActivity().getString(R.string.assistant_buick)) > -1) {
//                                application.setBuick(true);
//                            } else {
//                                application.setBuick(false);
//                            }
//                        }
//                        iChangeVehicleView.setLoading(false);
//                        iChangeVehicleView.switchVehicleSuccess();
//                    }
//                }, new Action1<Throwable>() {
//                    @Override
//                    public void call(Throwable throwable) {
//                        iChangeVehicleView.setLoading(false);
//                        iChangeVehicleView.onResponseError((OnStarException) throwable);
//                    }
//                });
    }

    private void changeOtherAccount() {
        AuthorService authorService = new AuthorService(iChangeVehicleView.onActivity());
        AuthTokenRequestEntity entity = BusinessUtil.createAuthTokenRequestEntity();
        subscription = authorService.pinReauthForNoPin(entity)
                .flatMap(new Func1<AuthPinTokenEntity, Observable<Subscriber>>() {
                    @Override
                    public Observable<Subscriber> call(AuthPinTokenEntity authPinTokenEntity) {
                        return new LoginSerice(iChangeVehicleView.onActivity()).loadUserProfile();
                    }
                })
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<Subscriber>() {
                    @Override
                    public void call(Subscriber subscriber) {
                        iChangeVehicleView.setLoading(false);
                        iChangeVehicleView.switchVehicleSuccess();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        OnStarException onStarException = (OnStarException) throwable;
                        iChangeVehicleView.onResponseError(onStarException);
                        iChangeVehicleView.setLoading(false);
                    }
                });
    }

}
